<?php
// 本类由系统自动生成，仅供测试用途
namespace Home\Controller;
use Think\Controller;
class ResponseController extends Controller {
    /*
     * 验证token
     */
    public function valid() {
        $echoStr = $_GET["echostr"];
        if ($this -> checkSignature()) {
            echo $echoStr;
            exit ;
        }
    }
    public function checkSignature()
    {
        define('TOKEN','weiapp');
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    /*
     * 响应信息
     */
    public function responseMsg($public_id)
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            switch ($RX_TYPE)
            {
                case "text":
                    $content_v="".$postObj->Content;
                    $resultStr = $this->textcheck($postObj,$public_id,$content_v);
                    break;
                case "event":
                    $event = A('Event');
                    $resultStr = $event->receiveEvent($postObj,$public_id);
                    break;
                case "voice":
                    $voiceopen=M("Voiceopen");
                    $result=$voiceopen->where("pub_id='$public_id'")->find();
                    if($result['isopen']==1){
                        $content_v="".$postObj->Recognition;
                        $resultStr = $this->textcheck($postObj,$public_id,$content_v);
                    }else{
                        $content="对不起！未开启语音识别功能！";
                        $resultStr = transmitText($postObj,$content);
                    }
                    break;
                default:
                    $key_menu=$postObj->FromUserName.'menu';
                    $resultStr = $this->textcheck($postObj,$public_id,S($key_menu));
                    //$resultStr = "";
                    break;
            }
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }
    public function returnmanu($public_id,$postObj){
        $plug=D('Plug');
        $member_public = D('Member_public');
        $textmenu=M("Textmenu");
        $pub_id=$member_public->where("public_id='$public_id'")->getField('id');
        $textmenu_list = $textmenu -> where("pub_id='$pub_id'")->order('key1')->select();
        foreach ($textmenu_list as $key=>$val){
            $p_id=$val['p_id'];
            $plug_name=$plug->where("id='$p_id'")->getField('plug_name');
            $textmenu_list[$key]['plug_name']=$plug_name;
        }
        $content="您好！请对应回复内容选择你需要的服务：\n\n";
        foreach ($textmenu_list as $key => $val){
            $content=$content."\"".$val['key1']."\""."    ".$val['plug_name']."\n";
        }
        $content=$content."\n回复‘？’回到主菜单。";
        $resultStr = transmitText($postObj,$content );
        return $resultStr;
    }
    /**
     * 文本菜单匹配回复内容
     * @param unknown $key1
     */
    public function textreturnmanu($public_id,$key1,$postObj){
        $resultStr="";
        $plug=M('Plug');
        $member_public = D('Member_public');
        $textmenu=M("Textmenu");
        $pub_id=$member_public->where("public_id='$public_id'")->getField('id');
        $p_id=$textmenu->where("key1='$key1' and pub_id='$pub_id'")->getField('p_id');
        if($p_id){
            $plug_list=$plug->where("id='$p_id'")->select();
            $extra_field=$plug_list[0]['extra_field'];
            if($extra_field==1){
                $url=$plug_list[0]['plug_home'];
                $a=substr($plug_list[0]['plug_home'],0,4);
                if($a!="http"){
                    $url=$_SERVER['SERVER_NAME']."/plug".$plug_list[0]['plug_home'];
                }
                $contentStr[] = array("Title" =>$plug_list[0]['plug_name'],
                    "Description" =>$plug_list[0]['intraduce'],
                    "PicUrl" =>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg",
                    "Url" =>$url);
                $resultStr = transmitNews($postObj, $contentStr);
            }else{
                $contentStr="";
                $contentStr=$contentStr."\"".$plug_list[0]['plug_name']."\""."使用指南：\n\n";
                $contentStr=$contentStr.$plug_list[0]['intraduce']."\n"."\n回复‘？’回到主菜单。";
                $resultStr = transmitText($postObj,  $plug_list[0]['intraduce']);
            }
        }
        return $resultStr;
    }
    /**
     * 自定义回复内容
     * @param unknown $key1
     */
    public function returncustom($public_id,$key1,$object){
        $resultStr="";
        $plug=M('Plug');
        $custom=M('Custom_res');
        $arr=C("TMPL_PARSE_STRING");
        $coutent=$custom->where("public_id='$public_id' and key1='$key1'")->find();
        switch ($coutent['msgtype']){
            case "text":
                $contentStr=$coutent['content'];
                $resultStr = transmitText($object, $coutent['content']);
                break;
            case "news":
                $contentStr[] = array("Title" =>$coutent['title'],
                "Description" =>$coutent['description'],
                "PicUrl" =>$arr['__PUBLIC__'].$coutent['picurl'],
                "Url" =>$coutent['url']);
                $resultStr = transmitNews($object, $contentStr);
                break;
            case "image":
                $media_id=$coutent['mediaid'];
                //$resultStr = transmitText($object, $media_id);
                $resultStr = transmitImage($object, $media_id);
                break;
            case "voice":
                $media_id=$coutent['mediaid'];
                $resultStr = transmitVoice($object, $media_id);
                break;
            case "video":
                $media_id=$coutent['mediaid'];
                $resultStr = transmitVideo($object, $coutent);
                break;
            case "music":
                $resultStr = transmitMusic($object, $coutent);
                break;
        }
        return $resultStr;
    }
    public function textcheck($postObj,$public_id,$value){
        $resultStr="";
        $plug=M('Plug');
        $member_public = D('Member_public');
        $textmenu=M("Textmenu");
        $pub_id=$member_public->where("public_id='$public_id'")->getField('id');
        $p_id=$textmenu->where("key1='$value' and pub_id='$pub_id'")->getField('p_id');
        $plug_list=$plug->where("id='$p_id'")->select();
        $url=$_SERVER['SERVER_NAME']."/plug".$plug_list[0]['plug_home'];
        $a=substr($plug_list[0]['plug_home'],0,4);
        if($a=="http"){
            $url=$plug_list[0]['plug_home'];
        }
        $key_menu=$postObj->FromUserName.'menu';
        switch ($value)
        {
            case "？":case "?":
                $resultStr = $this->returnmanu($public_id, $postObj);
                if($resultStr){
                    S($key_menu,"0");
                }
                break;
            default:
                if(S($key_menu)!="0"){
                    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
                    //$resultStr = transmitText($postObj,"已选择菜单“".$url."”"."\n回复‘？’回到主菜单。");
                    S($key_menu,S($key_menu));
                    $data=$postStr;
                    $resultStr = https_request(S($key_menu),$data);
                    //$resultStr = transmitText($postObj,  $resultStr);
                }else{
                    $resultStr = $this->textreturnmanu($public_id,$value,$postObj);
                    if($resultStr){
                        S($key_menu,$url);
                    }else{
                        $resultStr = $this->returncustom($public_id,$value,$postObj);
                        if(!$resultStr){
                            $resultStr = $this->callSimsimi($value);
                            //$resultStr = transmitText($postObj,$contentStr);
                        }
                    }
                }
                break;
        }
        return $resultStr;
    }
    public function callSimsimi($keyword)
    {
        $params['key'] = "2411036d095fe149abf2952492b3d469";
        $url = "http://www.tuling123.com/openapi/wechatapi?key=2411036d095fe149abf2952492b3d469";
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $resultStr = https_request($url,$postStr);
        return $resultStr;
    }
}
